<?php

namespace fakis\core\validators;

use fakis\core\base\DefineModel;
use yii\validators\Validator;

/**
 * 定义模型绑定验证器
 *
 * 在rule使用：
 * ['data', '\fakis\core\validators\DefineModelValidator', 'bind' => 'data'],
 *
 * @author Fakis <fakis738@qq.com>
 */
class DefineModelValidator extends Validator
{
    /**
     * 绑定的定义模型
     * @var string
     */
    public $bind;

    /**
     * 验证绑定的定义模型
     * @inheritDoc
     */
    public function validateAttribute($model, $attribute)
    {
        if ($model->hasErrors()) {
            return;
        }

        $name = $this->bind !== null ? $this->bind : $attribute;
        if (!method_exists($model, 'hasDefinedModel') || !$model->hasDefinedModel($name)) {
            $this->addError($model, $attribute, '没有绑定定义模型');
            return;
        }

        /** @var DefineModel $defineModel */
        $defineModel = $model->getDefinedModel($name);
        if (!$defineModel->validate()) {
            foreach ($defineModel->errors as $field => $errors) {
                foreach ($errors as $error) {
                    $this->addError($model, $attribute, "{$error} [{$field}]");
                }
            }
            return;
        }
    }
}
